<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="班级名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入班级名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="授课方式" prop="isVip">
        <el-select
          v-model="queryParams.isVip"
          placeholder="请选择授课方式"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in typeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="关联课程" prop="courseId">
        <el-select
          v-model="queryParams.courseId"
          placeholder="请选择关联课程"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in courseList"
            :key="item.id"
            :label="item.state === '1' ? item.name + '(已停用)' : item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班级老师" prop="teacherId">
        <el-select
          v-model="queryParams.teacherId"
          placeholder="请选择班级老师"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in teacherList"
            :key="item.value"
            :label="
              !item.isJob
                ? item.label + '(已离职)'
                : !item.isTeacher
                ? item.label + '(非授课)'
                : item.label
            "
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否结业" prop="beOver">
        <el-select
          v-model="queryParams.beOver"
          placeholder="是否结业"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_yes_no_2"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="是否已排课" prop="ifSchedule">
        <el-select
          v-model="queryParams.ifSchedule"
          placeholder="是否已排课"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_yes_no_2"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="只看我的班级" prop="ifMine">
        <div style="width: 240px">
          <el-switch
            v-model="queryParams.ifMine"
            active-value="0"
            inactive-value="1"
            @change="handleQuery"
          />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['registrar:class:add']"
          >新增班级</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="plain" plain icon="Upload" @click="handleImport"
          >导入班级</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="plain" plain icon="Download" @click="handleExport"
          >导出班级</el-button
        >
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList">
      </right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" border>
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" width="55" align="center">
        <template #default="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="班级名称"
        align="center"
        prop="name"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <router-link
            :to="{
              path: '/registrar/classDetail/index',
              query: {
                classId: scope.row.id,
                tab: 'first',
                repair: scope.row.isRepair,
                beOver: scope.row.beOver,
              },
            }"
            class="link-type"
          >
            <span>{{ scope.row.name }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        label="授课课程"
        align="center"
        prop="courseNameC"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column label="授课方式" align="center" prop="isVip" width="150">
        <template #default="scope">{{
          {
            "0": "1v1授课",
            "1": "班级授课",
          }[scope.row.isVip]
        }}</template>
      </el-table-column>
      <el-table-column label="班级老师" align="center" prop="teacherName" />
      <el-table-column
        label="人数/容量"
        align="center"
        prop="studentCount"
        width="100"
      >
        <template #default="scope">
          <span>
            {{
              scope.row.studentCount +
              "/" +
              (scope.row.plannedStudentCount === 0
                ? "未设置"
                : scope.row.plannedStudentCount)
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="已上/排课课次"
        align="center"
        prop="orderNum"
        width="150"
      >
        <template #default="scope">
          <span>
            {{ scope.row.soldOrderNum + "/" + scope.row.orderNum }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="已授课时"
        align="center"
        prop="classHour"
        width="100"
      />
      <el-table-column
        label="班级分类"
        align="center"
        prop="classTypeName"
        width="100"
      />
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.beOver == '0'" type="danger"> 结业 </el-tag>
          <el-tag v-else type="success"> 正常 </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <router-link
            :to="{
              path: '/registrar/classDetail/index',
              query: {
                classId: scope.row.id,
                tab: 'second',
                repair: scope.row.isRepair,
                beOver: scope.row.beOver,
              },
            }"
            class="link-type"
            v-if="scope.row.isRepair !== 0 && scope.row.beOver === '1'"
          >
            <el-button link type="primary">学员管理</el-button>
          </router-link>
          <router-link
            :to="{
              path: '/registrar/classDetail/index',
              query: {
                classId: scope.row.id,
                tab: 'third',
                repair: scope.row.isRepair,
                beOver: scope.row.beOver,
              },
            }"
            class="link-type"
            v-if="scope.row.beOver === '1'"
          >
            <el-button link type="primary">点名</el-button>
          </router-link>
          <el-button
            link
            type="primary"
            @click="handleGraduate(scope.row)"
            v-show="scope.row.isRepair !== 0 && scope.row.beOver === '1'"
            v-hasPermi="['registrar:class:edit']"
            >结业</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['registrar:class:edit']"
            v-show="scope.row.beOver === '1'"
            >编辑</el-button
          >
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['registrar:class:remove']"
            v-show="scope.row.beOver === '0'"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-drawer
      v-model="open"
      :title="title"
      :with-header="true"
      size="50%"
      class="class-drawer"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :before-close="closeW"
    >
      <div class="content">
        <el-form ref="classRef" :model="form" label-width="auto">
          <el-form-item
            label="班级名称"
            prop="name"
            :rules="[
              {
                required: true,
                message: '请输入班级名称',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="form.name"
              style="width: 240px"
              placeholder="请输入班级名称"
            />
          </el-form-item>
          <el-form-item
            label="授课方式"
            prop="isVip"
            :rules="[
              {
                required: true,
                message: '请选择授课方式',
                trigger: 'change',
              },
            ]"
          >
            <el-select
              v-model="form.isVip"
              placeholder="请选择授课方式"
              clearable
              style="width: 240px"
              @change="vipChange"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="关联课程"
            prop="courseIdArr"
            :rules="[
              {
                required: true,
                message: '请选择关联课程',
                trigger: 'change',
              },
            ]"
          >
            <el-select
              v-model="form.courseIdArr"
              placeholder="关联课程"
              clearable
              style="width: 240px"
              multiple
              :multiple-limit="form.isVip === '1' ? 2 : 1"
            >
              <el-option
                v-for="item in courseList2"
                :key="item.id"
                :label="item.state === '1' ? item.name + '(已停用)' : item.name"
                :value="item.id"
                :disabled="item.state === '1' || item.openClass === '0'"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="班级容量"
            :rules="[
              {
                required: true,
                message: '请输入班级容量',
                trigger: 'blur',
              },
            ]"
          >
            <el-input-number v-model="form.plannedStudentCount" :min="1" />
            <el-col :span="1" class="text-center"> </el-col>
            <el-radio-group v-model="form.excess">
              <el-radio :value="0" size="large">可超额</el-radio>
              <el-radio :value="1" size="large">不可超额</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="班级分类" prop="classType">
            <el-select
              style="width: 320px"
              v-model="form.classType"
              placeholder="请选择班级分类"
              clearable
            >
              <el-option
                v-for="item in classTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-button
              style="padding: 0 10px"
              type="primary"
              link
              @click="openClassType = true"
            >
              新增
            </el-button>
          </el-form-item>
          <el-form-item
            label="授课课时"
            prop="classHour"
            :rules="[
              {
                required: true,
                message: '请输入授课课时',
                trigger: 'blur',
              },
            ]"
          >
            <el-input-number v-model="form.classHour" :min="0" />
          </el-form-item>

          <el-form-item label="班级老师" prop="teacherId">
            <el-select
              v-model="form.teacherId"
              placeholder="班级老师"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="item in teacherList"
                :key="item.value"
                :label="
                  !item.isJob
                    ? item.label + '(已离职)'
                    : !item.isTeacher
                    ? item.label + '(非授课)'
                    : item.label
                "
                :value="item.value"
                :disabled="!item.isJob || !item.isTeacher"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model="form.remark"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitForm">
          {{ loading ? "保存中..." : "保存" }}
        </el-button>
      </template>
    </el-drawer>
    <el-dialog v-model="openClassType" title="班级分类设置" width="500">
      <el-button @click="handleAddClassType" type="primary"> 添加 </el-button>
      <el-form ref="classTypeRef" :model="classTypeForm" label-width="auto">
        <el-table
          class="quotation"
          :data="classTypeForm.copyClassTypeList"
          style="width: 100%; margin-top: 20px"
          max-height="400"
        >
          <el-table-column prop="name" label="班级分类名称">
            <template #default="scope">
              <el-form-item
                :prop="`copyClassTypeList.${scope.$index}.name`"
                :rules="[
                  {
                    required: true,
                    message: '请输入班级分类名称',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input v-model="scope.row.name"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click.prevent="handleDeleteClassType(scope.$index)"
                v-if="scope.row.used === '0'"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelClassTypeList()">取消</el-button>
          <el-button type="primary" @click="updateClassTypeList()">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ClassLesson">
import { getCourseListAPI } from "@/api/registrar/course";

import {
  getClassListAPI,
  saveClassAPI,
  updateClassAPI,
  getClassDetailAPI,
  deleteClassAPI,
  exportClassListAPI,
  //importClassListAPI,
} from "@/api/registrar/class";
import { getPeopleList } from "@/api/studentManagement/index";
import {
  getTLabelListAPI,
  updateTLabelListAPI,
} from "@/api/registrar/classroom";
import {
  getToken,
  getLoginDeptParentAuth,
  getLoginDeptAuth,
} from "@/utils/auth";

const { proxy } = getCurrentInstance();
const { sys_yes_no_2 } = proxy.useDict("sys_yes_no_2");

// 老师列表
const list = ref([]);
const teacherList = ref([]);
const courseList = ref([]); // 查询条件的课程，不做过滤操作
const courseList2 = ref([]); // 表单的课程，做过滤操作
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const classTypeList = ref([]);
const openClassType = ref(false);
const typeList = ref([
  { id: "1", name: "班课" },
  { id: "0", name: "一对一" },
]);

const data = reactive({
  form: {
    id: undefined,
    name: "",
    plannedStudentCount: 1, // 班级容量
    excess: 0, // 是否可超额
    isVip: null, // 是否一对一课程
    teacherId: null,
    beOver: "1", //结业状态
    classType: null, //班级分类id
    // classTypeName: null, // 班级分类名称
    courseIdArr: [], // 关联课程，多选
    courseId: null, // 关联课程--字符串逗号分隔
    classHour: 0, // 授课课时
    remark: null, // 备注
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: "",
    courseIdArr: [], // 关联课程，多选
    courseId: null, // 关联课程--字符串逗号分隔
    teacherId: null,
    beOver: null,
    ifSchedule: null, // 0是1否
    ifMine: "1", // 0是1否
    isVip: null,
  },
  classTypeForm: {
    copyClassTypeList: [],
  },
});

const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "导入班级",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: {
    Authorization: "Bearer " + getToken(),
    LoginDeptParentAuth: getLoginDeptParentAuth(),
    LoginDeptAuth: getLoginDeptAuth(),
  },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/tClass/importList",
});

const { queryParams, form, classTypeForm } = toRefs(data);

// 监听------------------------------------------------------------------------------------------------------------
watch(
  () => form.value.courseIdArr,
  (n, o) => {
    if (!n) n = [];
    form.value.courseId = n.join(",");
  }
);

// 方法-------------------------------------------------------------------------------------------------------------
// 获取教师列表
function getTeacherList() {
  loading.value = true;
  getPeopleList({ isTeach: 1 }).then((response) => {
    teacherList.value = response.data;
    loading.value = false;
  });
}

// 班级分类
function getClassTypeList() {
  loading.value = true;
  getTLabelListAPI({ lableType: "class_type" }).then((response) => {
    classTypeList.value = response.data;
    classTypeForm.value.copyClassTypeList = [...response.data];
    loading.value = false;
  });
}

// 班级分类保存
function updateClassTypeList() {
  proxy.$refs["classTypeRef"].validate((valid) => {
    if (valid) {
      loading.value = true;
      updateTLabelListAPI(classTypeForm.value.copyClassTypeList).then(() => {
        loading.value = false;
        openClassType.value = false;
        form.value.classType = "";
        getClassTypeList();
      });
    } else {
      proxy.$modal.msgError("教室名称不可为空过，请检查后再提交");
    }
  });
}

function cancelClassTypeList() {
  classTypeForm.value.copyClassTypeList = [...classTypeList.value];
  openClassType.value = false;
}

function handleAddClassType() {
  classTypeForm.value.copyClassTypeList.push({
    id: undefined,
    name: "",
    lableType: "class_type",
    used: "0",
  });
}

function handleDeleteClassType(index) {
  classTypeForm.value.copyClassTypeList.splice(index, 1);
}

function getList() {
  loading.value = true;
  getClassListAPI(proxy.addDateRange(queryParams.value, [])).then(
    (response) => {
      list.value = response.rows;
      total.value = response.total;
      loading.value = false;
    }
  );
}

// 获取关联课程
function getCourseList() {
  getCourseListAPI({ pageSize: 9999, pageNum: 1, open: 1 }).then((response) => {
    courseList.value = response.rows;
    loading.value = false;
  });
}

// 根据授课方式过滤课程
function getCourseListByIsVip(from) {
  loading.value = true;
  getCourseListAPI({
    pageSize: 9999,
    pageNum: 1,
    lessonType: form.value.isVip,
  }).then((response) => {
    courseList2.value = response.rows;
    let openId = null; // 当前限制仅一个公开课
    response.rows.forEach((element) => {
      if (element.openClass === "0") openId = element.id;
    });

    if (from) {
      if (form.value.isVip && form.value.isVip === "1" && openId)
        form.value.courseIdArr = [openId];
    }

    loading.value = false;
  });
}

/** 取消按钮 */
function closeW() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    name: "",
    plannedStudentCount: 1, // 班级容量
    excess: 0, // 是否可超额
    isVip: null, // 是否一对一课程
    teacherId: null,
    beOver: "1", //结业状态
    classType: null, //班级分类id
    // classTypeName: null, // 班级分类名称
    courseIdArr: [],
    courseId: null, // 关联课程，多选
    classHour: 0, // 授课课时
    remark: null, // 备注
  };
  proxy.resetForm("classRef");
}

function vipChange(value) {
  form.value.courseIdArr = [];
  courseList2.value = [];
  getCourseListByIsVip("vipchange");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  //dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  open.value = true;
  title.value = "新增班级";
}

function handleImport() {
  upload.open = true;
  //importClassListAPI().then((res) => {});
}
function handleExport() {
  let { name, courseId, teacherId, beOver, ifSchedule, ifMine, isVip } =
    queryParams.value;
  let param = {
    name,
    courseId,
    teacherId,
    beOver,
    ifSchedule,
    ifMine,
    isVip,
  };

  exportClassListAPI(param).then((res) => {
    let blob = new Blob([res], {
      type: "application/vnd.ms-excel;charset=utf-8",
    });
    //var contentDisposition = decodeURI(res.headers["content-disposition"]);
    const url = window.URL.createObjectURL(blob),
      link = document.createElement("a"); // 创建a标签
    link.href = url;
    link.download = "班级列表";
    link.click();
    URL.revokeObjectURL(url); // 释放内存
    proxy.$modal.msgSuccess("导出成功");
  });
}

/** 编辑按钮操作 */
function handleUpdate(row) {
  getCourseListByIsVip();
  getClassDetailAPI({ id: row.id }).then((response) => {
    form.value = response.data;
    form.value.isVip = form.value.isVip.toString();
    form.value.courseIdArr = form.value.courseId
      ? form.value.courseId.split(",")
      : [];
    getCourseListByIsVip();
    open.value = true;
    title.value = "编辑班级";
  });
}

function handleShow(row) {
  proxy.$modal.msgError("还未实现，敬请期待");
}

// 结业
function handleGraduate(row) {
  proxy.$modal
    .confirm(
      "班级结业后，学员将被移出班级，并且不能再对此班级排课。是否确定将班级结业？"
    )
    .then(function () {
      return updateClassAPI({ id: row.id, beOver: "0" });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["classRef"].validate((valid) => {
    if (valid) {
      if (form.value.isVip === "1") {
        if (form.value.courseIdArr.length < 2) {
          proxy.$modal.msgError("关联课程需包含1个非公开课");
          return;
        }
      }
      if (form.value.id != undefined) {
        updateClassAPI(form.value).then((response) => {
          proxy.$modal.msgSuccess("编辑成功");
          // 刷新班级分类
          getClassTypeList();
          getList();
          closeW();
        });
      } else {
        saveClassAPI(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          // 刷新班级分类
          getClassTypeList();
          getList();
          closeW();
        });
      }
    } else {
      proxy.$modal.msgError("表单校验未通过，请重新检查提交内容");
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm(
      '是否确认删除"' +
        row.name +
        '"？' +
        "删除后所有学员都将移出该班级，不能恢复。"
    )
    .then(function () {
      return deleteClassAPI({ id: row.id });
    })
    .then(() => {
      // 刷新班级分类
      getClassTypeList();
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 下载模板操作 */
function importTemplate() {
  proxy.$modal.msgError("下载模版暂未实现，请先使用本地模版，线上模版敬请期待");
  // proxy.download(
  //   "system/user/importTemplate",
  //   {},
  //   `user_template_${new Date().getTime()}.xlsx`
  // );
}

//调用---------------------------------------------------------------------------------------------------------------
getClassTypeList(); // 班级分类列表
getTeacherList();
getList();
getCourseList();
</script>
<style scoped lang="scss">
.state-box {
  cursor: pointer;
}
.el-table__row .el-form-item {
  margin: 0;
}
.title {
  color: #3a96fe;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
}
</style>
